package com.lxj.security.service.impl;

import com.lxj.security.mapper.SecurityMapper;
import com.lxj.security.service.SecurityService;
import com.lxj.utils.common.CommonResult;
import com.lxj.utils.entity.LoginParam;
import com.lxj.utils.entity.Permission;
import com.lxj.utils.entity.User;
import com.lxj.utils.util.JwtTokenUtil;
import io.jsonwebtoken.lang.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.HashSet;
import java.util.List;

@Service
public class SecurityServiceImpl implements SecurityService {
    @Autowired
    private SecurityMapper securityMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public CommonResult login(LoginParam loginParam) {
        String username = loginParam.getUsername();
        Assert.notNull(username, "账号必须不能为空");
        String password = loginParam.getPassword();
        Assert.notNull(password, "密码必须不能为空");
        User user = getUserByName(username);
        String password1 = user.getPassword();
        String encode = null;
        if (password.equals(password1)) {
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            encode = passwordEncoder.encode(password1);
        } else {
            encode = password1;
        }
        System.out.println(password1);
        boolean matches = passwordEncoder.matches(password, encode);
        if (matches) {
            List<Permission> permissionsByUserId = getPermissionsByUserId(user.getId());
            HashSet<Permission> Permissions = new HashSet<>(permissionsByUserId);
            user.setAuthorities(Permissions);
            String s = jwtTokenUtil.generateToken(user);
            return CommonResult.success(s);
        }
        return null;
    }

    @Override
    public CommonResult logout(String username) {
        Jedis jedis = new Jedis();
        Long username1 = jedis.del("username");
        if (username1!=null){
            return CommonResult.success(username1);
        }
        System.out.println(username1);
        return CommonResult.failed("失败");
    }

    private User getUserByName(String username) {
        User users = securityMapper.getByName(username);
        Assert.isTrue(users!=null, "您输入的账户不存在，或者有多个相同的账户");
        return users;
    }
    public List<Permission> getPermissionsByUserId(Integer id) {
        return securityMapper.getPermissionsByUserId(id);
    }
}
